package fileIO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class StudentDataIO {
	public static void main(String[] args) throws IOException {
		writeStudentTest();
		readStudentTest();
	}

	private static void writeStudentTest() throws IOException {
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("张狂", "男", 20));
		list.add(new Student("李明", "女", 22));
		list.add(new Student("王可金", "男", 29));
		writeStudent(list, new File("/home/tarena/Desktop/stu.txt"));
	}

	private static void writeStudent(List<Student> list, File file)
			throws IOException {
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(
				new FileOutputStream(file)));
		for (Student stu : list) {
			out.writeUTF(stu.getName());
			out.writeUTF(stu.getGender());
			out.write(stu.getAge());
		}
		out.close();
	}

	private static void readStudentTest() throws IOException {
		List<Student> list = readStudent(new File(
				"/home/tarena/Desktop/stu.txt"));
		Iterator<Student> i = list.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
		}

	}

	private static List<Student> readStudent(File file) throws IOException {
		DataInputStream in = new DataInputStream(new BufferedInputStream(
				new FileInputStream(file)));
		List<Student> list = new ArrayList<Student>();
		while(in.available()>0){
			Student s = new Student(in.readUTF(), in.readUTF(), in.read());
			list.add(s);
		}
		in.close();
		return list;

	}
}
